{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 单例模式\n",
    "# 保证一个类只有一个实例，并提供一个访问它的全局访问点\n",
    "# 1.构造函数私有化\n",
    "# 2.定义一个静态变量保存实例\n",
    "# 3.定义一个静态方法获取实例\n",
    "# 4.定义一个类方法判断实例是否存在\n",
    "# 多线程访问容易引发线程安全问题\n",
    "class Singleton(object):\n",
    "    \"\"\"单例模式类\"\"\"\n",
    "    __instance=None\n",
    "    def __new__(cls,*args,**kwargs):\n",
    "        if cls.__instance is None:\n",
    "            cls.__instance=super().__new__(cls)\n",
    "        return cls.__instance\n",
    "    @classmethod\n",
    "    def get_instance(cls):\n",
    "        return cls.__instance\n",
    "    @classmethod\n",
    "    def has_instance(cls):\n",
    "        return cls.__instance is not None\n",
    "s1=Singleton()\n",
    "print(s1.get_instance())\n",
    "s2=Singleton()\n",
    "print(s2.get_instance())\n",
    "print(s1 is s2)\n",
    "print(s1.get_instance() is s2.get_instance())\n",
    "print(Singleton.get_instance() is Singleton.get_instance())\n",
    "print(Singleton.has_instance())\n",
    "#通过导入参数的方式实现单例模式，但是不推荐，因为参数的修改会改变单例对象的引用\n",
    "# 模块就是天然的单例模式\n",
    "from singleton2 import Test as t1\n",
    "from singleton2 import Test as t2\n",
    "print(t1 is t2)\n",
    "# 隐藏方法\n",
    "print(Singleton.__doc__)#获取类的描述\n",
    "print(Singleton.__name__)#获取类名\n",
    "print(Singleton.__module__)#获取类所在的模块名\n",
    "print(Singleton.__bases__)#获取类的基类\n",
    "print(Singleton.__dict__)#获取类的所有属性和方法\n",
    "print(Singleton.__class__)#获取类的类型\n",
    "print(Singleton.__class__.__name__)#获取类的类型名\n",
    "print(Singleton.__str__)#获取类的字符串表示\n",
    "#__call__      对象被调用时触发\n",
    "class Test(object):\n",
    "    def __init__(self):\n",
    "        print(\"init\")\n",
    "    def __call__(self):\n",
    "        print(\"call\")\n",
    "t=Test()\n",
    "t()\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
